﻿using System.Collections.Specialized;
using System.Globalization;
using System.Text.RegularExpressions;

namespace XiaoSe.Collections.Specialized
{
    /// <summary>
    /// 键值帮助类
    /// </summary>
    public class NameValueCollectionHelper
    {
        private NameValueCollection _nvc = null;
        public void CreateFromString(string str)
        {
            const string sRegex = @"[\w]+=[\w]+";
            var matchs = Regex.Matches(str, sRegex, RegexOptions.IgnoreCase);
            if (matchs.Count <= 0)
            {
                return;
            }
            _nvc = new NameValueCollection();
            foreach (Match m in matchs)
            {
                var sNameValue = m.Value.Split('=');
                _nvc.Add(sNameValue[0], sNameValue[1]);
            }
        }
        public string GetValueByKey(string key)
        {
            if (_nvc == null)
            {
                return null;
            }
            return _nvc[key] != null ? _nvc[key].ToString(CultureInfo.InvariantCulture) : null;
        }
        public int GetValueByKeyToInt(string key)
        {
            string sValue = GetValueByKey(key);
            if (string.IsNullOrEmpty(sValue))
            {
                return 0;
            }
            int iResult;
            return int.TryParse(sValue, out iResult) ? iResult : 0;
        }
    }
}
